package com.hbusa.cotroller.login;

import cn.hutool.db.Session;
import com.hbusa.dto.TbUser;
import com.hbusa.service.UserService;
import com.hbusa.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.xml.transform.sax.SAXSource;
import java.io.IOException;

/**
 * @author XiaoXin
 * @date 2021/12/25 - 2:42
 */

@WebServlet("/admin/doLogin")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String autoLogin = req.getParameter("autoLogin");
        System.out.println(username);
        System.out.println(password);
        System.out.println("autoLogin:" + autoLogin);
        UserService userService = new UserServiceImpl();
        TbUser tbUser = userService.queryByUsernameAndPassword(username, password);
        System.out.println(tbUser);
        if (tbUser != null) {
            Cookie usernameCookie = new Cookie("username", username);
            usernameCookie.setPath(req.getContextPath());
            Cookie passwordCookie = new Cookie("password", password);
            passwordCookie.setPath(req.getContextPath());
            if ("on".equals(autoLogin)) {
                usernameCookie.setMaxAge(5 * 24 * 60 * 60);
                usernameCookie.setPath("/");
            }
            resp.addCookie(usernameCookie);
            resp.sendRedirect("/index.jsp");
        } else {
            req.getRequestDispatcher("/admin/choose.jsp").forward(req, resp);
        }
    }
}
